using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using ZSW.Framework.UIElement;
using TMPro;
using Main.Event;
using System;

namespace Main.UI
{
    public class UI_Time : ZSWF_BaseUIElement
    {
        public RectTransform DayNightRect;
        public RectTransform ClockParent;
        public Image SeasonImage;
        public TextMeshProUGUI DateTime;
        public TextMeshProUGUI TodayTime;
        public Sprite[] SeasonIcons;
        private List<GameObject> clockBlocks = new List<GameObject>();

        public override void Init()
        {
            base.Init();

            for (int i = 0; i < ClockParent.childCount; i++)
            {
                int index = i;
                clockBlocks.Add(ClockParent.GetChild(index).gameObject);
                clockBlocks[index].SetActive(false);
            }
        }

        private void OnEnable()
        {
            MainEventSystem.GameDayEvent += OnDayChangeEvent;
            MainEventSystem.GameDateEvent += OnDateChangeEvent;
        }

        private void OnDisable()
        {
            MainEventSystem.GameDayEvent -= OnDayChangeEvent;
            MainEventSystem.GameDateEvent -= OnDateChangeEvent;
        }


        private void OnDateChangeEvent(int day, int month, int year, Season season)
        {
            // 日期
            DateTime.text = year.ToString("D4") + "年" + month.ToString("D2") + "月" + day.ToString("D2") + "日";
            // 季节
            SeasonImage.sprite = SeasonIcons[(int)season];
        }

        private void SwitchDayNight(int hour)
        {
            int angle = hour * 15 - 90;
            DayNightRect.DORotate(new Vector3(0, 0, angle), 0.5f, RotateMode.Fast).SetEase(Ease.OutQuad);
        }


        /// <summary>
        /// 切换时间图片
        /// </summary>
        /// <param name="hour"></param>
        private void SwitchHourClock(int hour)
        {

            int showIndex = hour / 4;
            for (int i = 0; i < clockBlocks.Count; i++)
            {
                int index = i;
                clockBlocks[i].SetActive(index < showIndex);
            }
        }

        private void OnDayChangeEvent(int second, int minute, int hour, int day, Season _)
        {
            // 文字更新
            TodayTime.text = hour.ToString("D2") + ":" + minute.ToString("D2");

            SwitchHourClock(hour);

            SwitchDayNight(hour);
        }
    }
}